/**
 * 用户信息
 */
import Routine from '@/utils/routine.js';

import {
	tokenExpires
} from '@/config';

import * as userInfoApi from '@/api/UserInfo/index.js';


const DEFAULTSTATE = {
	TIMERSTATUS:false,
	accessToken: null, // token
	id:null,//用户id
	nickName: '', //用户昵称
	avatar: '', //用户头像
	phone:null,//移动电话
	isVip: false, //会员身份
	vipExpire:'',//会员有效期
}

export default {
	namespaced: true,
	state: Object.assign({}, DEFAULTSTATE),
	mutations: {
		setState(state, payload) {
			Object.keys(payload).forEach(key => {
				state[key] = payload[key];
			})
		},
	},
	getters: {
		// 用户信息展示
        getUserInfoValue(state){
			let {avatar,isVip,nickName,vipExpire}=state;
			return {avatar,isVip,nickName,vipExpire}
		}
	},
	actions: {
		// 获取用户信息
		async getUserInfo({
			commit,state
		}) {
			if(state.id) return false;
			let res = await userInfoApi.userInfo();
			if (res.code === 0) {
				commit('setState', res.data);
			}
		},
		// 获取token
		async getToken({
			dispatch,commit,state
		}) {
			let TIMERSTATUS=state.TIMERSTATUS;
			if(!TIMERSTATUS){
				commit('setState', {TIMERSTATUS:true});
				let func=null;
				// #ifdef MP
				    func= await dispatch('wxToken')
				// #endif
				if(func) await func();
				commit('setState', {TIMERSTATUS:false});
			   return false;
			}
			let TIMER=null;
			return new Promise((reslove,reject)=>{
				TIMER=setInterval(()=>{
					let TIMERSTATUS=state.TIMERSTATUS;
					if(!TIMERSTATUS){
						clearInterval(TIMER);
						reslove();
					}
				},300);
			})
		},
		async wxToken({
			commit
		}){
			// 登录
			const TOKENJSON = uni.getStorageSync('_TOKEN') || JSON.stringify({});
			// #ifdef MP
			let {
				ACCESSTOKEN = null, UPDATETIME = 0
			} = JSON.parse(TOKENJSON);
			if ((!!UPDATETIME) && (!!ACCESSTOKEN) && (Date.now() - UPDATETIME) < tokenExpires) {
				commit('setState', {
					accessToken: ACCESSTOKEN
				});
			} else {
				let code = await Routine.getCode();
				let res = await Routine.authUserInfo(code);
				if (res.code === 0) {
					let {
						accessToken
					} = res.data;
					let ACCESSTOKEN = JSON.stringify({
						ACCESSTOKEN: accessToken,
						UPDATETIME: Date.now()
					});
					uni.setStorageSync('_TOKEN', ACCESSTOKEN);
					commit('setState', {
						accessToken: accessToken
					});
				}
			}
			// #endif
		}
	}
}